import { Message, Loading } from 'element-ui'
import axios from 'axios'
import qs from 'querystring'
import isEmpty from 'lodash.isempty'

const CODE_SUCCESS = '200'
const CODE_SESSION_EXPIRE = '1002'
const NO_VIEW_RECORD_PERMISSION = '424'

const METHODS = {
  GET: 'get',
  POST: 'post',
  PUT: 'put',
  DELETE: 'delete'
}
// var reqNum = 0
// axios.interceptors.request.use(function (config) {
//   // 在请求发出之前进行一些操作，每次发出请求就 reqNum++
//   reqNum++
//   Loading.service()
//   return config
// })
// axios.interceptors.response.use(response => {
//   // 接受请求后 reqNum--，判断请求所有请求是否完成
//   reqNum--
//   if (reqNum <= 0) {
//     Loading.service().close()
//   } else {
//     Loading.service()
//   }
//   return response
// })

const request = (
  url,
  params,
  headers = {},
  method = METHODS.POST,
  jsonType = true
) => {
  var options = {
    headers: {
      'Content-Type': jsonType
        ? 'application/json;charset=UTF-8'
        : 'application/x-www-form-urlencoded'
    },
    method: method,
    responseType: 'json'
  }
  if (method !== METHODS.GET && !isEmpty(params)) {
    // 文件上传
    if (headers === 'file') {
      delete options.headers['Content-Type']
      let formData = new FormData()
      formData.append('file', params.file)
      options.headers['Content-Type'] = 'multipart/form-data'
      options.data = formData
    } else {
      options.data = jsonType
        ? JSON.stringify(params)
        : qs.stringify(params)
    }
  } else if (method === METHODS.GET && !isEmpty(params)) {
    const newParams =
      (~url.lastIndexOf('?') ? '&' : '?') + qs.stringify(params)
    url += newParams
  }
  url = window.config.context + url
  return axios(url, options)
    .then(checkRespStatus)
    .catch((error) => {
      if (!error.code && !navigator.onLine) {
        // 因无网络而出错的情况
        Message.error({
          message: '网络出错，请重试',
          type: 'error',
          showClose: false
        })
      }
      return new Promise((resolve, reject) => {
        // 返回错误回调
        reject(error)
      })
    })
}

const checkRespStatus = (resp) => {
  if (resp.status !== 200) {
    return window.Promise.reject('Server error occurred')
  }
  // 等价于 fetch respPromise.json().then(resp => {}); 的 resp;
  // 服务端响应的json字段
  let data = resp.data
  return new Promise((resolve, reject) => {
    if (resp && data.code === CODE_SUCCESS) {
      resolve(data.data)
    } else if (resp && data.code === CODE_SESSION_EXPIRE) {
      history.go(-1)
      Message.error({
        message: '您还没有登录, 请登录后再试',
        type: 'error',
        showClose: false
      })
    } else if (resp && data.code === NO_VIEW_RECORD_PERMISSION) {
      history.go(-1)
      Message.error({
        message: '您没有权限访问',
        type: 'error',
        showClose: false
      })
    } else {
      reject(data)
      Message.error({
        message: data.msg,
        type: 'error',
        showClose: false,
        duration: 3000
      })
    }
  })
}
const POST = (url, params, headers) =>
  request(url, params, headers, METHODS.POST, true)
export const GET = (url, params, headers) =>
  request(url, params, headers, METHODS.GET, true)
const obj = {
  post: POST,
  get: GET
}
export default obj
